from django.conf import settings

def auto_config():

    auto = getattr(settings, "DJMD_UPLOAD_AUTO_CONFIG", False) 
    config_done = getattr(settings, "DJMD_UPLOAD_AUTO_CONFIG_DONE", False)

    if not auto or config_done:
        return


    if getattr(settings, "MEDIA_URL") == "":
        setattr(settings, "MEDIA_URL", "/media/")

    if getattr(settings, "MEDIA_ROOT") == "":

        import os

        media_root = os.path.join(getattr(settings, "BASE_DIR"), "media")
        setattr(settings, "MEDIA_ROOT", media_root)

    if not hasattr(settings, "DJMD_UPLOAD_PATH"):
        setattr(settings, "DJMD_UPLOAD_PATH", "djmd")

    # dynamically adding urlpatterns
    from django.utils.module_loading import import_string
    from django.conf.urls import url, include

    local_urlconf = import_string(settings.ROOT_URLCONF)

    local_urlconf.urlpatterns.append(url(r'^djmd/', include("djmd.urls")))

    from django.views.static import serve

    local_urlconf.urlpatterns.append(url(f"^{settings.MEDIA_URL.strip('/')}/(?P<path>.*)", serve, {"document_root": settings.MEDIA_ROOT}))

    # the urlconf just modified (local_urlconf) is local to the thread and not global, and 
    # I cannot find a way to make the change global, so I store the local urlconf as a workaround
    setattr(settings, "DJMD_THREAD_LOCAL_URLCONF", local_urlconf)
